<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>涨跌统计</title>
    <script src="js/echarts.min.js"></script>
    <script src="js/common.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0 20px 0 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            font-family: Arial, sans-serif;
        }
        .container {
            width: 90%;
            max-width: 1200px;
            margin-top: 10px;
            margin-bottom: 20px;
        }
        .upper-section {
            display: flex;
            justify-content: space-between;
        }
        .chart-container {
            width: 48%;
            height: 400px;
            border: 1px solid #eee;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .middle-section {
            width: 100%;
            min-height: 150px;
            border: 1px solid #eee;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            flex-wrap: wrap;
            margin-top: 20px;
            gap: 10px; /* 添加间距 */
            padding: 15px 0px;
        }
        .stock-item {
            width: 100px; /* 固定宽度 */
            height: 50px; /* 固定高度 */
            background: linear-gradient(to bottom, rgba(246, 181, 181, 0.5), rgba(251, 251, 251, 0.05)); /* 渐变背景 */
            border-radius: 5px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 15px 0;
            text-align: center;
        }
        .stock-name {
            font-weight: bold;
            color: #383838;
            font-size: 14px;
            margin-bottom: 5px;
        }
        .stock-price {
            font-size: 16px;
            color: #52c41a; /* 默认绿色 */
            margin-bottom: 5px;
        }
        .change-info {
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #666;
        }
        .change-info div{
            margin:0 5px;
        }
        .upDownAnalysisSection {
            width: 100%;
            min-height: 300px;
            border: 1px solid #eee;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-top: 20px;
        }
        .chart-group {
            width: 48%;
            height: auto;
            border: 1px solid #eee;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
        }
        #barChart {
            height: 300px;
        }
        .tab-container {
            width: 100%;
        }
        .tab-header {
            display: flex;
            border-bottom: 1px solid #eee;
        }
        .tab-item {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
        }
        .tab-item.active {
            border-bottom: 2px solid #1890ff;
            color: #1890ff;
            font-weight: bold;
        }
        .tab-content {
            height: 500px; /* 设置固定高度 */
            overflow-y: auto; /* 添加垂直滚动条 */
            margin-top: 10px;
            /* 隐藏滚动条样式但保留滚动功能 */
            scrollbar-width: none; /* Firefox */
            -ms-overflow-style: none; /* IE和Edge */
        }
        .tab-content::-webkit-scrollbar {
            display: none; /* Chrome, Safari, Opera */
        }
        .tab-content table {
            width: 100%;
            border-collapse: collapse;
            display: none;
        }
        .tab-content table.active {
            display: table;
        }
        .tab-content th, .tab-content td {
            padding: 10px;
            text-align: center;
            border-bottom: 1px solid #eee;
            font-size: 13px;
            color: #999999;
        }
        .tab-content th.sortable {
            cursor: pointer;
        }
        .tab-content th.sortable:hover {
            background-color: #f5f5f5;
        }
        .stock-name {
            font-weight: bold;
            color: #383838;
            font-size: 14px;
        }
        .stock-code {
            font-size: 12px;
            color: #666;
        }
        .table-stock-price {
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 新增图片显示容器 -->
        <div id="imageModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.8); z-index: 9999; justify-content: center; align-items: center;">
            <img id="fullScreenImage" style="max-width: 90%; max-height: 90%;">
        </div>
        
        <!-- 新增K线图模态框 -->
        <div id="kLineModal" style="display: none; position: fixed;padding: 20px 0 0 10px; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.6); z-index: 10000; justify-content: center; align-items: center;">
            <div style="width: 90%; height: 100%; background: white; border-radius: 8px; display: flex; flex-direction: column;">
                <div style="display: flex; justify-content: space-between;  background: #fff; border-radius: 8px 8px 0 0;">
                    <h3 id="kLineTitle" style="margin: 0;padding-left: 75px;margin-top: 10px">K线图</h3>
                </div>
                <iframe id="kLineFrame" style="flex: 1; width: 100%; border: none; border-radius: 0 0 8px 8px; margin-top: -10px"></iframe>
            </div>
        </div>
        
        <div class="upper-section">
            <div class="chart-group" style="display: flex">
                <div id="barChart"></div>
                <div>
                    <span id="medianValue" style="display: block; text-align: center; font-size: 15px;"></span>
                </div>
                <div id="zddb">
                </div>
            </div>
            <div id="pieChart" class="chart-container"></div>
        </div>
        <div class="middle-section" id="middle-section">
            <!-- 中间部分待定 -->
        </div>
        <div class="upDownAnalysisSection" id="upDownAnalysisSection">
            <div class="tab-container">
                <div class="tab-header">
                    <div class="tab-item active" data-type="zt">涨停池</div>
                    <div class="tab-item" data-type="lb">连板池</div>
                    <div class="tab-item" data-type="zb">炸板池</div>
                    <div class="tab-item" data-type="dt">跌停池</div>
                </div>
                <div class="tab-content">
                    <table id="ztTable" class="active">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>股票/代码</th>
                                <th class="sortable" data-sort="price">现价</th>
                                <th class="sortable" data-sort="change">涨跌幅</th>
                                <th class="sortable" data-sort="days">连续涨停数</th>
                                <th>动因</th>
                                <th>板块</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <table id="lbTable">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>股票/代码</th>
                                <th class="sortable" data-sort="price">现价</th>
                                <th class="sortable" data-sort="change">涨跌幅</th>
                                <th class="sortable" data-sort="days">连续涨停数</th>
                                <th>动因</th>
                                <th>板块</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <table id="zbTable">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>股票/代码</th>
                                <th class="sortable" data-sort="price">现价</th>
                                <th class="sortable" data-sort="change">涨跌幅</th>
                                <th>板块</th>
                                <th>动因</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <table id="dtTable">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>股票/代码</th>
                                <th class="sortable" data-sort="price">现价</th>
                                <th class="sortable" data-sort="change">涨跌幅</th>
                                <th>动因</th>
                                <th>板块</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 初始化图表
        const barChart = echarts.init(document.getElementById('barChart'));
        const pieChart = echarts.init(document.getElementById('pieChart'));
        
        // 柱状图配置
        const barOption = {
            title: {
                text: '涨跌分布',
                left: 'center',
                padding: [20, 0, 0, 0]
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: params => {
                    const data = params[0].data;
                    return `${data.range}: ${data.value}只`;
                }
            },
            grid: {
                bottom: 0,
                top: 60,
                left: '3%',
                right: '4%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: ['跌停', '-10%', '-8%', '-6%', '-4%', '-2%', '0%', '2%', '4%', '6%', '8%', '10%', '涨停'],
                axisLabel: {
                    rotate: 45
                },
                boundaryGap: true,
                axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: {
                type: 'value',
                name: '数量(只)',
                minInterval: 1
            },
            series: [{
                name: '涨跌家数',
                type: 'bar',
                itemStyle: {
                    color: function(params) {
                        if (params.dataIndex === 6) {
                            return '#bfbfbf';
                        }
                        return params.dataIndex < 6 ? '#52c41a' : '#f5222d';
                    }
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}'
                },
                data: [],
                xAxisIndex: 0,
                animationDuration: 1500
            }]
        };

        // 饼图配置
        const pieOption = {
            title: {
                text: '涨跌比例',
                left: 'center',
                textStyle: {
                    fontWeight: 'bold'
                },
                padding: [23, 0, 0, 0]
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a}<br/>{b}: {c}只 ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                bottom: 35,
                data: ['上涨', '平盘', '下跌', '停牌']
            },
            series: [{
                name: '涨跌比例',
                type: 'pie',
                radius: ['30%', '50%'],
                center: ['50%', '45%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 5,
                    borderColor: '#fff',
                    borderWidth: 1,
                    color: function(params) {
                        // 自定义颜色
                        const colorList = ['#f5222d', '#bfbfbf', '#52c41a', '#728ef4'];  // 新增：黄色用于停牌
                        return colorList[params.dataIndex];
                    }
                },
                label: {
                    show: true,
                    formatter: '{b}: {c}只\n({d}%)',
                    fontSize: 16
                },
                labelLine: {
                    length: 10,
                    length2: 20
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    },
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold'
                    }
                },
                data: []
            }]
        };

        // 设置初始配置
        barChart.setOption(barOption);
        pieChart.setOption(pieOption);

        function renderPoolTable(data, type) {
            const tableId = type + 'Table';
            const table = document.getElementById(tableId);
            const tbody = table.querySelector('tbody');
            tbody.innerHTML = '';
            
            const poolData = data.data || [];
            
            poolData.forEach((item, index) => {
                const row = document.createElement('tr');
                
                // 序号列
                const indexCell = document.createElement('td');
                indexCell.innerHTML = index + 1;
                row.appendChild(indexCell);
                
                // 股票名称和代码
                const nameCell = document.createElement('td');
                nameCell.innerHTML = `<div class="stock-name">${item.secu_name}</div>
                                <div class="stock-code">${item.secu_code}</div>`;
                // 添加双击事件打开K线图
                nameCell.style.cursor = 'pointer';
                nameCell.addEventListener('dblclick', function() {
                    openKLineModal(item.secu_code, item.secu_name);
                });
                row.appendChild(nameCell);
                
                // 现价
                const priceCell = document.createElement('td');
                priceCell.innerHTML = `<span class="table-stock-price" style="color:${formatNumberColor(item.last_px)}">${item.last_px}</span>`;
                row.appendChild(priceCell);
                
                // 涨跌幅
                const changeCell = document.createElement('td');
                changeCell.innerHTML = `<span class="table-stock-price" style="color:${formatNumberColor(item.change)}">${formatNumber(item.change * 100,2,1)}%</span>`;
                row.appendChild(changeCell);
                
                // 连续涨停数 (仅涨停池和连板池)
                if (type === 'zt' || type === 'lb') {
                    let limit_up_days_name = (item.limit_up_days === 1 ? "首板" : item.limit_up_days+ "连板");
                    const daysCell = document.createElement('td');
                    daysCell.innerHTML = `<span style="font-weight: bold">${limit_up_days_name}</span>`;
                    row.appendChild(daysCell);
                }

                // 动因
                const reasonCell = document.createElement('td');
                const reasonText = item.up_reason || '-';
                reasonCell.innerHTML = `
                    <div style="max-width: 300px; 
                               display: -webkit-box;
                               -webkit-line-clamp: 2;
                               -webkit-box-orient: vertical;
                               overflow: hidden;
                               text-overflow: ellipsis;
                               font-size: 12px;
                               color: #383838;
                               text-align: center;
                               margin: 0 auto;"
                         title="${reasonText}">
                        ${reasonText}
                    </div>`;
                row.appendChild(reasonCell);

                // 板块
                const plateCell = document.createElement('td');
                const plates = item.plate || [];
                const colorList = ['#1890ff', '#13c2c2', '#722ed1', '#fadb14', '#fa8c16', '#eb2f96'];
                
                // 最多显示8个标签，两行
                const displayPlates = plates.slice(0, 8);
                const hasMore = plates.length > 8;
                
                plateCell.innerHTML = `
                    <div style="display: -webkit-box;
                               -webkit-line-clamp: 2;
                               -webkit-box-orient: vertical;
                               overflow: hidden;
                               max-width: 300px;">
                        ${displayPlates.map((plate, index) => {
                            const color = colorList[index % colorList.length];
                            return `<span style="display: inline-block;
                                       padding: 2px 6px;
                                       margin: 2px;
                                       border-radius: 4px;
                                       background-color: ${color};
                                       color: white;
                                       font-size: 12px;">
                                ${plate.secu_name}
                            </span>`;
                        }).join('')}
                        ${hasMore ? `<span style="display: inline-block;
                                   padding: 2px 6px;
                                   margin: 2px;
                                   border-radius: 4px;
                                   background-color: #f5f5f5;
                                   color: #666;
                                   font-size: 12px;
                                   cursor: pointer;"
                              title="${plates.slice(8).map(p => p.secu_name).join('\n')}">
                            ...
                        </span>` : ''}
                    </div>
                `;
                row.appendChild(plateCell);
                
                tbody.appendChild(row);
            });
        }

        // 封装数据加载和渲染逻辑
        function loadAndRenderTableData() {
            const activeTab = document.querySelector('.tab-item.active');
            const type = activeTab.getAttribute('data-type');
            let apiType = '';
            switch(type) {
                case 'zt': apiType = 'up_pool'; break;
                case 'lb': apiType = 'continuous_up_pool'; break;
                case 'zb': apiType = 'up_open_pool'; break;
                case 'dt': apiType = 'down_pool'; break;
            }

            fetch(`http://localhost:8110/common/stock/V2/getUpDownAnalysis?type=${apiType}`)
                .then(response => response.json())
                .then(data => {
                    // 检查接口状态
                    if (data.code !== 200) {
                        console.error('接口异常:', data.message || '未知错误');
                        return;
                    }

                    renderPoolTable(data, type);
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                });
        }

        // 封装数据加载和渲染逻辑
        function loadAndRenderData() {
            fetch('http://localhost:8110/common/stock/V2/zdStatistics')
                .then(response => response.json())
                .then(data => {
                    // 检查接口状态
                    if (data.code !== 200) {
                        console.error('接口异常:', data.message || '未知错误');
                        barChart.setOption({
                            series: [{
                                data: []
                            }]
                        });
                        pieChart.setOption({
                            series: [{
                                data: []
                            }]
                        });
                        return;
                    }

                    // 计算涨跌中位数
                    let zwsChange = data.data.up_down_dis.average_rise || 0;
                    zwsChange = (zwsChange * 100).toFixed(2);
                    const medianElement = document.getElementById('medianValue');
                    medianElement.innerHTML = `<span style="padding-left: 15px;color: #666">涨跌中位数：</span><span style="color:${formatNumberColor(zwsChange)};">${zwsChange}%</span>`
                    + `<span style="padding-left: 25px;color: #666">市场热度：</span><span style="color:${formatNumberColorByPassNumber(data.data.market_degree,60)};">${ data.data.market_degree}°</span>`
            medianElement.style.color = 'black';

                    // 渲染涨跌平水平条形图
                    const zddbElement = document.getElementById('zddb');
                    const fallNum = data.data.up_down_dis.fall_num || 0;
                    const flatNum = data.data.up_down_dis.flat_num || 0;
                    const riseNum = data.data.up_down_dis.rise_num || 0;
                    const total = fallNum + flatNum + riseNum;

                    zddbElement.innerHTML = `
                        <div style="
                            width: calc(100% - 40px);
                            height: 15px;
                            display: flex;
                            border-radius: 4px;
                            overflow: hidden;
                            margin: 10px 20px 0 20px;
                        ">
                            <div style="
                                flex: ${total === 0 ? 1 : fallNum};
                                background: #52c41a;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                color: white;
                                font-weight: bold;
                                margin-right: 2px;
                            ">${fallNum}</div>
                            <div style="
                                flex: ${total === 0 ? 1 : flatNum};
                                background: #bfbfbf;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                color: white;
                                font-weight: bold;
                                margin-right: 2px;
                            ">${flatNum}</div>
                            <div style="
                                flex: ${total === 0 ? 1 : riseNum};
                                background: #f5222d;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                color: white;
                                font-weight: bold;
                            ">${riseNum}</div>
                        </div>
                        <div style="
                            width: calc(100% - 40px);
                            display: flex;
                            justify-content: space-between;
                            margin: 5px 20px;
                            font-size: 14px;
                            color: #666;
                        ">
                            <span>今日成交额: ${data.data.shsz_balance}</span>

                            <span>较昨日此时: <span style="color:${formatNumberColorByStr(data.data.shsz_balance_change_px)}">${data.data.shsz_balance_change_px}</span></span>
                        </div>
                    `;

                    // 处理柱状图数据，使用up_down_dis字段
                    const upDownData = data.data.up_down_dis || {};
                    const barData = [
                        { value: upDownData.down_num || 0, range: '跌停' },
                        { value: upDownData.down_10 || 0, range: '跌幅 8%~10%' },
                        { value: upDownData.down_8 || 0, range: '跌幅 6%~8%' },
                        { value: upDownData.down_6 || 0, range: '跌幅 4%~6%' },
                        { value: upDownData.down_4 || 0, range: '跌幅 2%~4%' },
                        { value: upDownData.down_2 || 0, range: '跌幅 0%~2%' },
                        { value: upDownData.flat_num || 0, range: '平盘' },
                        { value: upDownData.up_2 || 0, range: '涨幅 0%-2%' },
                        { value: upDownData.up_4 || 0, range: '涨幅 2%-4%' },
                        { value: upDownData.up_6 || 0, range: '涨幅 4%~6%' },
                        { value: upDownData.up_8 || 0, range: '涨幅 6%~8%' },
                        { value: upDownData.up_8 || 0, range: '涨幅 8%~10%' },
                        { value: upDownData.up_num || 0, range: '涨停' }
                    ];
                    barChart.setOption({
                        series: [{
                            data: barData
                        }]
                    });

                    // 处理饼图数据
                    const pieData = [
                        { value: upDownData.rise_num, name: '上涨' },
                        { value: upDownData.flat_num || 0, name: '平盘' },
                        { value: upDownData.fall_num, name: '下跌' },
                        { value: upDownData.suspend_num || 0, name: '停牌' }
                    ];
                    pieChart.setOption({
                        series: [{
                            data: pieData
                        }]
                    });

                    // 新增：渲染中间部分股票信息
                    const stockList = data.data.stock_list || [];
                    renderMiddleSection(stockList);
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                    // 保持图表为空但显示状态
                    barChart.setOption({
                        series: [{
                            data: []
                        }]
                    });
                    pieChart.setOption({
                        series: [{
                            data: []
                        }]
                    });
                });
        }

        // 初始加载
        loadAndRenderData();

        loadAndRenderTableData();

        // 设置定时任务，每隔5秒刷新一次
        setInterval(loadAndRenderData, getRefreshInterval(5000,30000));

        // 窗口大小变化时重绘图表
        window.addEventListener('resize', function() {
            barChart.resize();
            pieChart.resize();
        });

        // 添加选项卡切换事件
        document.querySelectorAll('.tab-item').forEach(tab => {
            tab.addEventListener('click', function() {
                // 切换选项卡状态
                document.querySelectorAll('.tab-item').forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                
                // 切换表格显示
                const type = this.getAttribute('data-type');
                document.querySelectorAll('.tab-content table').forEach(t => t.classList.remove('active'));
                document.getElementById(type + 'Table').classList.add('active');
                
                // 重新加载数据
                loadAndRenderTableData();
            });
        });

        // 添加排序功能
        document.querySelectorAll('.sortable').forEach(th => {
            th.addEventListener('click', function() {
                const type = document.querySelector('.tab-item.active').getAttribute('data-type');
                const table = document.getElementById(type + 'Table');
                const tbody = table.querySelector('tbody');
                const rows = Array.from(tbody.querySelectorAll('tr'));
                const sortKey = this.getAttribute('data-sort');
                
                // 获取当前排序方向
                const currentDir = this.getAttribute('data-sort-dir') || 'desc';
                const newDir = currentDir === 'desc' ? 'asc' : 'desc';
                this.setAttribute('data-sort-dir', newDir);
                
                // 清除其他表头的排序方向
                document.querySelectorAll('.sortable').forEach(el => {
                    if (el !== this) {
                        el.removeAttribute('data-sort-dir');
                    }
                });
                
                rows.sort((a, b) => {
                    const aValue = a.cells[['price', 'change', 'days'].indexOf(sortKey) + 1].textContent;
                    const bValue = b.cells[['price', 'change', 'days'].indexOf(sortKey) + 1].textContent;
                    
                    let comparison = 0;
                    if (sortKey === 'days') {
                        comparison = parseInt(bValue || 0) - parseInt(aValue || 0);
                    } else {
                        comparison = parseFloat(bValue || 0) - parseFloat(aValue || 0);
                    }
                    
                    // 根据排序方向调整比较结果
                    return newDir === 'desc' ? comparison : -comparison;
                });
                
                tbody.innerHTML = '';
                rows.forEach(row => tbody.appendChild(row));
            });
        });

        function renderMiddleSection(stocks) {
            const middleSection = document.getElementById('middle-section');
            middleSection.innerHTML = ''; // 清空现有内容

            stocks.forEach(stock => {
                const stockItem = document.createElement('div');
                stockItem.className = 'stock-item';
                stockItem.setAttribute('data-searchcode', stock.searchCode);
                // 添加鼠标悬停计时器
                let hoverTimer;
                stockItem.addEventListener('mouseenter', function() {
                    hoverTimer = setTimeout(() => {
                        const searchCode = this.getAttribute('data-searchcode');
                        const timestamp = new Date().getTime();
                        const imgUrl = `http://localhost:8110/common/stock/getMinImg?searchCode=${searchCode}&time=${timestamp}`;
                        document.getElementById('fullScreenImage').src = imgUrl;
                        document.getElementById('imageModal').style.display = 'flex';
                    }, 1600); // 1.6秒延迟
                });

                // 鼠标离开时清除计时器
                stockItem.addEventListener('mouseleave', function() {
                    clearTimeout(hoverTimer);
                });

                // 添加双击事件监听器
                stockItem.addEventListener('dblclick', function() {
                    const searchCode = this.getAttribute('data-searchcode');
                    const stockName = this.querySelector('.stock-name').textContent;
                    openKLineModal(searchCode, stockName);
                });

                //字体颜色
                var fontColor = stock.name !== '离岸人民币' ? formatNumberColor(stock.zde || stock.zf) : fontColor = formatNumberColor( stock.zde * -1 );
                //背景色
                var backGroundColor;
                if( stock.zde >= 0  ){
                    backGroundColor = stock.name === '离岸人民币' ? `linear-gradient(to bottom, rgba(205, 248, 209, 0.3), rgba(251, 251, 251, 0.05))` : `linear-gradient(to bottom, rgba(246, 181, 181, 0.3), rgba(251, 251, 251, 0.05))` ;
                }else{
                    backGroundColor = stock.name === '离岸人民币' ? `linear-gradient(to bottom, rgba(246, 181, 181, 0.3), rgba(251, 251, 251, 0.05))` : `linear-gradient(to bottom, rgba(205, 248, 209, 0.3), rgba(251, 251, 251, 0.05))` ;
                }

                const stockName = document.createElement('div');
                stockName.className = 'stock-name';
                stockName.textContent = stock.name;

                const stockPrice = document.createElement('div');
                stockPrice.className = 'stock-price';
                stockPrice.textContent = `${stock.nowPrice}${stock.name == '两市市值' ? "万亿" : ''}`;
                stockPrice.style.color = fontColor;

                const changeInfo = document.createElement('div');
                changeInfo.className = 'change-info';

                const changeAmount = document.createElement('div');
                if( stock.zde ){
                    changeAmount.textContent = `${stock.zde}`;
                    changeAmount.style.color = fontColor;
                }
                const changePercent = document.createElement('div');
                if( stock.zde ){
                    changePercent.textContent = `${stock.zf}%`;
                    changePercent.style.color = fontColor;
                }
                changeInfo.appendChild(changeAmount);
                changeInfo.appendChild(changePercent);
                stockItem.appendChild(stockName);
                stockItem.appendChild(stockPrice);
                stockItem.appendChild(changeInfo);
                stockItem.style.background = backGroundColor;
                middleSection.appendChild(stockItem);
            });

            // 添加点击关闭图片事件
            document.getElementById('imageModal').addEventListener('click', function(e) {
                if (e.target === this || e.target === document.getElementById('fullScreenImage')) {
                    this.style.display = 'none';
                }
            });

            // 添加ESC键关闭图片事件
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && document.getElementById('imageModal').style.display === 'flex') {
                    document.getElementById('imageModal').style.display = 'none';
                }
            });
        }

        // 打开K线图模态框函数
        function openKLineModal(searchCode, stockName) {
            const kLineModal = document.getElementById('kLineModal');
            const kLineFrame = document.getElementById('kLineFrame');
            const kLineTitle = document.getElementById('kLineTitle');
            kLineTitle.textContent = `${stockName}-${searchCode}`;
            kLineFrame.src = `stockKLine.html?searchCode=${searchCode}`;
            kLineModal.style.display = 'flex';
        }

        // 点击模态框外部关闭
        document.getElementById('kLineModal').addEventListener('click', function(e) {
            if (e.target === this) {
                const kLineModal = document.getElementById('kLineModal');
                const kLineFrame = document.getElementById('kLineFrame');
                kLineModal.style.display = 'none';
                kLineFrame.src = '';
            }
        });

        // ESC键关闭K线图模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const kLineModal = document.getElementById('kLineModal');
                const kLineFrame = document.getElementById('kLineFrame');
                if (kLineModal.style.display === 'flex') {
                    kLineModal.style.display = 'none';
                    kLineFrame.src = '';
                }
            }
        });
        
    </script>
</body>
</html>